#include "PublicUtils.h"
#include "HashSet.h"


/**
 * @brief 接收指定字节个数
 * @return 1 接收成功
 * @return 0 对方断线
*/
int recvn(int netfd, void *buf, long length){
	ssize_t recived = 0;
	while (recived != length){
		ssize_t byte = recv(netfd, buf, length - recived, MSG_WAITALL);
        if(byte == 0){
            return 0;
        }
        // printf("recived %ld\n", recived);
		recived += byte;
	}
	return 1;
}

/* 添加epoll监听 */
int addEpoll(int epoll_fd, int fd){
	struct epoll_event event_socket;
	event_socket.events = EPOLLIN;			/* 读取 */
	event_socket.data.fd = fd;	/* 指定文件描述符 */
	epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event_socket);

    return 0;
}


/**
 * @brief 根据key从config文件中返回需要的value值
*/
int getValueByKeyFromConfig(char *key, char *value) {
   FILE *file = fopen("config/config.ini", "r");
	while (1) {
		char line[100];
      memset(line,0,sizeof(line));
		// 读一行数据
		char *res = fgets(line, sizeof(line), file);
		if (res == NULL) {
			char buf[] = "没有要找的内容 \n";
			memcpy(value, buf, strlen(buf));
			return -1;
		}
		// 处理数据
		char *line_key = strtok(line, "=");
		if (strcmp(key, line_key) == 0) {
			// 要找的内容
			char *line_value = strtok(NULL, "=");
			memcpy(value, line_value, strlen(line_value) - 1);
			return 0;
		}
	}

	return 0;
}


/**
 * @brief 从配置文件中获取ip
*/
char *getIpFromConfig(){
   char *ip = (char *)calloc(100, sizeof(char));
   getValueByKeyFromConfig("ip",ip);
   return ip;
}

/**
 * @brief 从配置文件中获取port
*/
char *getPortFromConfig() {
   char *port = (char *)calloc(100, sizeof(char));
   getValueByKeyFromConfig("port",port);
   return port;
}


char *getUserFromConfig(){
   char *user = (char *)calloc(100, sizeof(char));
   getValueByKeyFromConfig("user", user);
   return user;
}

char *getPasswdFromConfig(){
   char *passwd = (char *)calloc(100, sizeof(char));
   getValueByKeyFromConfig("passwd", passwd);
   return passwd;
}

char *getDatabaseFromCOnfig(){
   char *database = (char *)calloc(100, sizeof(char));
   getValueByKeyFromConfig("database", database);
   return database;
}

void get_salt(char *salt,char *passwd) {
    int i,j;
    //取出 salt,i 记录密码字符下标,j 记录$出现次数
    for(i=0,j=0; passwd[i] && j != 3; ++i) {
        if(passwd[i] == '$') {
            ++j;
        }
    }
    strncpy(salt, passwd, i-1);
}


void initSlotQueue(CircularQueue *slotQueue){
    for(int i = 0; i < slotQueue->capacity; i++){
        HashSet *set = create_hashset(10);
        slotQueue->enqueue(slotQueue, set);
    }
}


void initTimer(){
    struct itimerval timer;
    memset(&timer, 0, sizeof timer);
    timer.it_value.tv_sec = 1;
    timer.it_value.tv_usec = 0;    
    timer.it_interval.tv_sec = 1;
    timer.it_interval.tv_usec = 0;
    setitimer(ITIMER_REAL, &timer, NULL);   
}



void printmd5(unsigned char *md){
    for (int i = 0; i < 16; i++) {
        printf("%02x", md[i]);
    }
    printf("\n");
}